﻿using Ocelot.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Ocelot_Consul
{
    public class MyCache : IOcelotCache<CachedResponse>
    {
        private static Dictionary<string, CacheDataModel> CustomCacheDictionary = new Dictionary<string, CacheDataModel>();


        public void Add(string key, CachedResponse value, TimeSpan ttl, string region)
        {
            Console.WriteLine($"this is {nameof(MyCache)},{nameof(Add)}");
            CustomCacheDictionary[key] = new CacheDataModel
            {
                CachedResponse = value,
                Region = region,
                Timeout = DateTime.Now.Add(ttl)
            };
        }

        public void AddAndDelete(string key, CachedResponse value, TimeSpan ttl, string region)
        {
            Console.WriteLine($"this is {nameof(MyCache)},{nameof(AddAndDelete)}");

            CustomCacheDictionary[key] = new CacheDataModel
            {
                CachedResponse = value,
                Region = region,
                Timeout = DateTime.Now.Add(ttl)
            };
        }

        public void ClearRegion(string region)
        {
            Console.WriteLine($"this is {nameof(MyCache)},{nameof(ClearRegion)}");

            var leyList = CustomCacheDictionary.Where(k => k.Value.Region == region).Select(v => v.Key);
            foreach (var item in leyList)
            {
                CustomCacheDictionary.Remove(item);
            }
        }

        public CachedResponse Get(string key, string region)
        {
            Console.WriteLine($"this is {nameof(MyCache)},{nameof(Get)}");

            if (CustomCacheDictionary.ContainsKey(key) && CustomCacheDictionary[key] != null && CustomCacheDictionary[key].Timeout > DateTime.Now && CustomCacheDictionary[key].Region.Equals(region))
            {
                return CustomCacheDictionary[key].CachedResponse;
            }
            else
            {
                return null;
            }

        }

        private class CacheDataModel
        {
            public CachedResponse CachedResponse { get; set; }

            public DateTime Timeout { get; set; }

            public string Region { get; set; }
        }
    }
}
